package com.firewolf.rbac.log.core;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Method;


/**
 * 作者：刘兴
 * 时间:19/2/20
 **/
@Aspect
public class LogAspect {

    @Autowired
    private LogProperties logProperties;

    @Autowired
    private LogService logService;

    @Autowired
    private UserInfoService userInfoService;

    @Pointcut("@annotation(com.firewolf.rbac.log.core.OperationLog)")
    public void pc() {
    }

    @Around("pc()")
    public Object saveLog(ProceedingJoinPoint joinPoint) {
        try {

            long start = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();//继承执行被切的方法，这里就是hello()方法
            long end = System.currentTimeMillis();

            String packages = logProperties.getPackages();
            String toPackage = joinPoint.getTarget().getClass().getPackage().getName(); //要执行的类所在的包
            boolean b = isNeedSaveLog(packages, toPackage);
            if (b) {
                String methodName = joinPoint.getSignature().toLongString();

                //获取操作的方法
                Method[] methods = joinPoint.getTarget().getClass().getDeclaredMethods();
                String operate = "";
                for (Method m : methods) {
                    if (m.toString().equals(methodName)) { //找到被调用的方法
                        OperationLog logObj = m.getDeclaredAnnotation(OperationLog.class);
                        operate = logObj.opreate(); //获取注解里面设置的操作信息
                        break;
                    }
                }

                //获取当前登录的用户名
                Object username = userInfoService.getCurrentUserName();

                //构造一个日志对象
                Log log = new Log();
                log.setTime(end - start);
                log.setArgs(joinPoint.getArgs());
                log.setMethod(methodName);
                log.setOperate(operate);
                log.setUsername(username.toString());

                //记录日志
                logService.saveLog(log);
            }
            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;

    }


    /**
     * 当前操作是否需要记录日志
     *
     * @param packages
     * @param toPackage
     * @return
     */
    private boolean isNeedSaveLog(String packages, String toPackage) {

        if (packages == null)
            return true;
        String[] split = packages.split(",");
        for (String s : split) {
            if (toPackage.contains(s))
                return true;
        }
        return false;
    }

}
